#include "cortexm4.h"
#include "interrupt.h"
#include "thread.h"

/* customize, trigger a PENDSV interrupt */
void mx_thread_schedule ()
{
    /* record the CPU interrupt state */
    mx_usize_t istate = mx_interrupt_disable_nest();
    /* trigger PENDSV interrupt */
    CM4_SCB->ICSR |= CM4_SCB_ICSR_PENDSVSET_Msk;
    /* force enable interrupt for PENDSV */
    mx_interrupt_enable();
    /* recover CPU interrup state */
    mx_interrupt_enable_nest(istate);
}

/* the PENDSV interrupt handle */
static void pendsv_intr_handler (mx_void_pt param)
{
    /* need do schedule before exit the pendsv interrupt */
    mx_thread_schedule_interrupt_need();
}

static void pendsv_intr_register ()
{
    /* register the pendsv interrupt */
    mx_interrupt_register("pendsv-int14", 14, pendsv_intr_handler, mx_null);
}
MX_BOARDINIT_EXPORT(pendsv_intr_register, 0);
